package com.yuanlai.quartz.service.impl;


import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.DateBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.DateBuilder.IntervalUnit;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuanlai.quartz.mapper.TtimedTaskMapper;
import com.yuanlai.quartz.model.TtimedTask;
import com.yuanlai.quartz.model.enums.JobStatusEnum;
import com.yuanlai.quartz.model.vo.TaskVo;
import com.yuanlai.quartz.service.ITaskService;
import com.yuanlai.quartz.utils.PageInfoUtil;
import com.yuanlai.quartz.utils.QuartzUtil;



@Service
public class TaskServiceImpl implements ITaskService {
	public final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private QuartzUtil quartzUtil;
    
    @Autowired
    private TtimedTaskMapper timedTaskMapper;
    
	
	@Override
	public void initWhenStart(List<TaskVo> list) {		
		// 循环
		for (TaskVo taskVo : list) {
			 //正常"开启"状态的
			 if (JobStatusEnum.RUNNING.getCode().equals(taskVo.getJobStatus())) {
				 quartzUtil.addJobToStartSchedule(taskVo);//把任务注册到调度中
			}
		}
		
	 
		
	}


	@Override
	public PageInfoUtil queryTask(int limit ,int pageNum,TtimedTask record) {
		// TODO Auto-generated method stub
		PageHelper.startPage(pageNum, limit);
		List<TtimedTask> selecteList = timedTaskMapper.selectByCondition(record);
		//取记录总条数
        PageInfo<TtimedTask> pageInfo = new PageInfo<TtimedTask>(selecteList);
		System.out.println("查询结果："+selecteList.size());
		long total = pageInfo.getTotal();
		List<TaskVo> voList=new ArrayList<TaskVo>();
		if (!CollectionUtils.isEmpty(selecteList)) {
			for (TtimedTask entity : selecteList) {
				TaskVo vo=new TaskVo();
				BeanUtils.copyProperties(entity, vo);
				voList.add(vo);
			}
			
		}
		PageInfoUtil pageInfoUtil=new PageInfoUtil(total, voList);
		return pageInfoUtil;
	}


	@Override
	public TaskVo queryOne(Long id) {
		// TODO Auto-generated method stub
		TtimedTask entity = timedTaskMapper.selectById(id);
		TaskVo vo=new TaskVo();
		BeanUtils.copyProperties(entity, vo);
		return vo;
	}


	@Override
	public int addTask(TtimedTask record) {
		// TODO Auto-generated method stub
		return timedTaskMapper.insertSelective(record);
	}


	@Override
	public int updateTask(TtimedTask record) {
		// TODO Auto-generated method stub
		return timedTaskMapper.updateSelective(record);
	}


	@Override
	public int deleteTask(Long id) throws SchedulerException {
		// TODO Auto-generated method stub
		//删除任务
		 TtimedTask selectedTask = timedTaskMapper.selectById(id);
		 TaskVo taskVo=new TaskVo();
		 BeanUtils.copyProperties(selectedTask, taskVo);
		 quartzUtil.deleteJob(taskVo);
		return timedTaskMapper.remove(id);
	}





	@Override
	public List<TaskVo> selectAllTask() {
		// TODO Auto-generated method stub

    List<TtimedTask> selecteList = timedTaskMapper.selectAll();
		
		List<TaskVo> voList=new ArrayList<TaskVo>();
		if (!CollectionUtils.isEmpty(selecteList)) {
			for (TtimedTask entity : selecteList) {
				TaskVo vo=new TaskVo();
				BeanUtils.copyProperties(entity, vo);
				voList.add(vo);
			}
			
		}
		
		return voList;
	}


	 /**
	  * 立即执行一次
	 * @throws ClassNotFoundException 
	  */
	@Override
	public void runTaskNow(Long id) throws SchedulerException {
		// TODO Auto-generated method stub
		 TtimedTask selectedTask = timedTaskMapper.selectById(id);
		 TaskVo taskVo=new TaskVo();
		 BeanUtils.copyProperties(selectedTask, taskVo);
		 quartzUtil.runJobNow(taskVo);
	}


	/**
	 * 关闭任务状态
	 * @throws SchedulerException 
	 */
	@Override
	public void closeTask(Long id) throws SchedulerException {
		// TODO Auto-generated method stub
		 TtimedTask record = timedTaskMapper.selectById(id);
		 TaskVo taskVo=new TaskVo();
		 BeanUtils.copyProperties(record, taskVo);
		 
		 record.setJobStatus(JobStatusEnum.CLOSE.getCode());		
		 timedTaskMapper.updateSelective(record);
		 
		 quartzUtil.deleteJob(taskVo);
		 

	}


	/**
	 * 开启任务
	 */
	@Override
	public void openTask(Long id) {
		// TODO Auto-generated method stub
		 TtimedTask record = timedTaskMapper.selectById(id);
		 TaskVo taskVo=new TaskVo();
		 BeanUtils.copyProperties(record, taskVo);
		 record.setJobStatus(JobStatusEnum.RUNNING.getCode());		
		 timedTaskMapper.updateSelective(record);
		 
		 quartzUtil.addJobToStartSchedule(taskVo);

		 
	}


	@Override
	public void pauseTask(Long id) throws SchedulerException {
		// TODO Auto-generated method stub
		 TtimedTask selectedTask = timedTaskMapper.selectById(id);
		 TaskVo taskVo=new TaskVo();
		 BeanUtils.copyProperties(selectedTask, taskVo);
		 quartzUtil.pauseJob(taskVo);
	}


	@Override
	public void resumeTask(Long id) throws SchedulerException {
		// TODO Auto-generated method stub
		TtimedTask selectedTask = timedTaskMapper.selectById(id);
		 TaskVo taskVo=new TaskVo();
		 BeanUtils.copyProperties(selectedTask, taskVo);
		 quartzUtil.resumeJob(taskVo);
	}


	/**
	 * 修改cron
	 * @throws SchedulerException 
	 */
	@Override
	public void updateTaskCron(TaskVo editedCronVo) throws SchedulerException {
		// TODO Auto-generated method stub
		TtimedTask task = timedTaskMapper.selectById(editedCronVo.getId());
		 TaskVo taskVo=new TaskVo();
		 BeanUtils.copyProperties(task, taskVo);
		 if ((JobStatusEnum.RUNNING.getCode()).equals(task.getJobStatus())) {
			 //如果当前任务处在运行状态  则把修改后的cron表达式传递进去，以便重新触发任务
			 taskVo.setCronExpression(editedCronVo.getCronExpression());
			 quartzUtil.updateCronExpression(taskVo);
		}

		 task.setCronExpression(editedCronVo.getCronExpression());
		 timedTaskMapper.updateSelective(task);//把修改后的表达式保存	
		
	}


	
	


	

	

}
